package com.sanjin.mall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.sanjin.mall.authserver.feign.MemberFeign;
import com.sanjin.mall.authserver.feign.SmsFeign;
import com.sanjin.mall.authserver.vo.UserRegisterVo;
import com.sanjin.mall.common.constant.AuthConstant;
import com.sanjin.mall.common.exception.BizCodeEnume;
import com.sanjin.mall.common.utils.R;
import com.sanjin.mall.common.vo.MemberRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class RegisterController {

    @Autowired
    SmsFeign smsFeign;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MemberFeign memberFeign;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@PathParam("phone") String phone) {
        //TODO 1、接口防刷。

        String redisCode = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000){
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //2、验证码的再次校验。redis。存 key-phone,value-code  sms:code:15884430987  -> 45678
        String code = String.valueOf(((Math.random()*9+1)*100000));
        String subCode = code + "_" + System.currentTimeMillis();
        System.out.println("code = " + code);
        // redis缓存验证码，防止同一个phone在60秒内再次发送验证码
        //set(K var1, V var2, long var3, TimeUnit var5)
        stringRedisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX+phone,subCode,10, TimeUnit.MINUTES);

        smsFeign.send(code, phone);

        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes, HttpSession session) {
        System.out.println("test" + result.hasErrors());
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            // model.addAttribute("errors", errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.mall.com/reg.html";
        }

        //1、校验验证码
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)){
            if (code.equals(s.split("_")[0])){
                //删除验证码；令牌机制
                stringRedisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证通过。//真正注册。调用远程服务进行注册。
                MemberRegistVo memberRegistVo = new MemberRegistVo();
                memberRegistVo.setUserName(vo.getUserName());
                memberRegistVo.setPhone(vo.getPhone());
                memberRegistVo.setPassword(vo.getPassword());
                R r = memberFeign.regist(memberRegistVo);
                if (r.getCode() == 0) {
                    //成功
                    return "redirect:http://auth.mall.com/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getMessage(new TypeReference<String>() {}));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.mall.com/reg.html";
                }
            }else{
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.mall.com/reg.html";
            }
        }
        else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.mall.com/reg.html";
        }
    }
}
